<?
//RC4
include "rc4.php";

//gets mode based on refferer
function get_auth_mode() {
	global $_AUTH_MODES;
	foreach($_AUTH_MODES as $wildcard => $name) {
		if(fnmatch($wildcard, $_SERVER["HTTP_REFFERER"], FNM_CASEFOLD))
			$mode = $name;
	}
	return $mode;
}

function mysql_prep_string($str) {
	return $str?$str:" ";
}

function send_mail_to_user($email, $message, $subject){
	
}

function is_session_authentificated() {	
	if(!usession_get('authentificated'))
		return false;
	if(!check_user_exists(usession_get('email')))
		return false;
	return true;
}

function number_of_user_installs(){
	global $_DB;
	$qemail = $_DB->prepare("SELECT COUNT(*) FROM `user` where 1"); $qemail->execute();
	$count=$qemail->fetchColumn();
	return $count;
}

function next_level($count=false){
	global $_DB;
	if(!$count) $count=number_of_user_installs();
	$qemail = $_DB->prepare("SELECT `treshold` FROM `songs` WHERE `treshold` > {$count} limit 0,1"); $qemail->execute();
	$level=$qemail->fetchColumn();
	return $level;
}

function next_song($treshold=false){
	global $_DB;
	if(!$treshold) $treshold=number_of_user_installs();
	$qemail = $_DB->prepare("SELECT `title` FROM `songs` WHERE `treshold` > :treshold limit 1"); $qemail->execute(array('treshold'=>$treshold));
	$title=$qemail->fetchColumn();
	return $title;	
}

function number_of_songs_available($treshold=false){
	global $_DB;
	if(!$treshold) $treshold=number_of_user_installs();
	$qemail = $_DB->prepare("SELECT count(*) FROM `songs` WHERE `treshold` < :treshold"); $qemail->execute(array('treshold'=>$treshold));
	$count=$qemail->fetchColumn();
	return $count;	
}

function check_user_exists($email) {
	global $_DB;
	$qemail = $_DB->prepare("SELECT COUNT(*) FROM `user` WHERE `email` =  :email"); $qemail->execute(array('email'=>$email));
	if($qemail->fetchColumn() == 1)
		return true;
	else
	 return false;
}

function usession_set($key, $value) {
	$_SESSION['User'][$key]=$value;
}

function usession_get($key) {
	return $_SESSION['User'][$key]; 
}

function song_hash($file,$title,$length){
	return sha1(md5($file.rand()).md5(time())).crc32($length.md5($title)).sha1(time().rand());
}

function get_songFromHash($hash) {
	global $_DB;
	$song= $_DB->prepare("SELECT * FROM `songs` WHERE `hash` =  :hash"); $song->execute(array('hash'=>$hash));
	return $song->fetch();
}

function hexToString($hex) {
    $string='';
    for ($i=0; $i < strlen($hex)-1; $i+=2)
    {
        $string .= chr(hexdec($hex[$i].$hex[$i+1]));
    }
    return $string;
}

function get_userInfo($email=false) {
	if(!$email) $email=usession_get('email');
	global $_DB;
	$userInfo= $_DB->prepare("SELECT * FROM `user` WHERE `email` =  :email"); $userInfo->execute(array('email'=>$email));
	return $userInfo->fetch();
}

function generate_key() {
	return bin2hex(md5(uniqid(rand(),1)));
}

function updateAndSetUserData($email,$data) {
	global $_DB;
	if(!check_user_exists($email)) {
		$_DB->prepare("INSERT INTO `user`(`email`) VALUES(:email)")->execute(array('email'=>$email));
	}
	//gen DB-QUERY
	foreach(array_keys($data) as $key) {
		if($dbstr) $dbstr .= ", ";
		$dbstr .= "`$key` = :$key";
	}
	$query=$_DB->prepare("UPDATE `user` SET $dbstr WHERE `email` = :orig_email LIMIT 1");$query->execute(array_merge($data, array('orig_email'=>$email)));
}

function user_hasSongPlayRights($song,$userInfo=false){
	if(!is_session_authentificated()) return 0;
	if(is_string($song)) $song=get_songFromHash($song);
	if(number_of_user_installs() <= $song['treshold']) return -1;
	if(!$userInfo) $userInfo = get_userInfo();
	$rights=explode(",",$song['rights']);
	foreach($userInfo as $key => $value) {
		if(substr($key,0,5)=="auth_" and $value==1) {
			if(in_array(substr($key,5),$rights)) return 1;
		}
	}
	return 0;
}

function myErrorHandler($errorcode, $errordesc, $errorfile, $errorline)
{
    switch ($errorcode) {
		case E_USER_ERROR:
			$message= "Error: FATAL [$errorcode] $errordesc in line $errorline ($errorfile)";
			break;

		case E_USER_WARNING:
			$message= "Error: WARNING [$errorcode] $errordesc in line $errorline ($errorfile)";
			break;

		case E_USER_NOTICE:
			$message=false;
			break;

		default: //(unknown)
			//~ $message= "Error: UNKNOWN [$errorcode] $errordesc in line $errorline ($errorfile)";
			$message=false;
			break;
    }
	if($message)	
		logi($message);

    return true;
}

function logi($message) {
	file_put_contents('/root/Dropbox/inlegend_app/error_log',date('m.d.Y H:i:s')." $message\n", FILE_APPEND);
}


function validEmail($email)
{
   $isValid = true;
   $atIndex = strrpos($email, "@");
   if (is_bool($atIndex) && !$atIndex)
   {
      $isValid = false;
   }
   else
   {
      $domain = substr($email, $atIndex+1);
      $local = substr($email, 0, $atIndex);
      $localLen = strlen($local);
      $domainLen = strlen($domain);
      if ($localLen < 1 || $localLen > 64)
      {
         // local part length exceeded
         $isValid = false;
      }
      else if ($domainLen < 1 || $domainLen > 255)
      {
         // domain part length exceeded
         $isValid = false;
      }
      else if ($local[0] == '.' || $local[$localLen-1] == '.')
      {
         // local part starts or ends with '.'
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $local))
      {
         // local part has two consecutive dots
         $isValid = false;
      }
      else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain))
      {
         // character not valid in domain part
         $isValid = false;
      }
      else if (preg_match('/\\.\\./', $domain))
      {
         // domain part has two consecutive dots
         $isValid = false;
      }
      else if
(!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/',
                 str_replace("\\\\","",$local)))
      {
         // character not valid in local part unless 
         // local part is quoted
         if (!preg_match('/^"(\\\\"|[^"])+"$/',
             str_replace("\\\\","",$local)))
         {
            $isValid = false;
         }
      }
      if ($isValid && !(checkdnsrr($domain,"MX") || checkdnsrr($domain,"A")))
      {
         // domain not found in DNS
         $isValid = false;
      }
   }
   return $isValid;
}

?>